﻿using __Able.Network.Connection;
using __Able.Network.Packets;
using __Able.Network.RequestPacket;

namespace __Able.Network.Events
{
    public class BasicFamilyProcessor : IPacketListener
    {
        private Channel channel;

        public BasicFamilyProcessor(Channel channel)
        {
            this.channel = channel;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inpacket"></param>
        public void PacketArrived(_InPacket inpacket)
        {
            if (inpacket is UnknownRequestPacket)
            {
                channel.PacketManager.OnReceivedUnknownPacket(new EventArgs<UnknownRequestPacket>((UnknownRequestPacket)inpacket));
                return;
            }

            if (inpacket is ErrorPacket)
            {
                ErrorPacket error = (ErrorPacket)inpacket;
                if (error.ErrorType == ErrorPacketType.ERROR_TIMEOUT)
                {
                    channel.PacketManager.OnSendPacketTimeOut(new EventArgs<_OutPacket>(error.TimeOutPacket));
                }
                else
                {
                    channel.OnError(new EventArgs<ErrorPacket>((ErrorPacket)inpacket));
                }
                return;
            }

            // 现在开始判断包的类型，作出相应的处理
            ConnectionPolicy policy = channel.ConnectionManager.GetConnection(inpacket.PortName).Policy;
            // 根据输入包，检索对应的输出包
            _OutPacket outpacket = policy.RetrieveSent(inpacket);

            switch (inpacket.Command)
            {
                case (ushort)_Command.CMD_GCCP:
                    ProcessReceive(inpacket, outpacket);
                    break;

                // 未知命令忽略掉
                case (ushort)_Command.CMD_UNKNOWN:
                    break;

                // 其他情况我们删除超时队列中的包
                default:
                    channel.PacketManager.RemoveResendPacket(inpacket);
                    channel.PacketManager.OnSentPacketSuccessfully(new EventArgs<_OutPacket, _InPacket>(outpacket, inpacket));
                    break;
            }
        }
        /// <summary>
        /// 处理接收信息
        /// </summary>
        /// <param name="inpacket"></param>
        /// <param name="outpacket"></param>
        private void ProcessReceive(_InPacket inpacket, _OutPacket outpacket)
        {
            //var e = new EventArgs<_InPacket>(packet);
        }

        public bool Accept(Packets._InPacket inPacket)
        {
            return inPacket.GetFamily() == (uint)_ProtocolFamily.PROTOCOL_FAMILY_BASIC;
        }
    }
}
